<template>
  <div class="exams-management">
    <h2 class="page-title">考试管理</h2>
    <div class="actions">
      <button @click="showAddExamModal" class="btn btn-primary">
        <i class="fas fa-plus"></i> 添加新考试
      </button>

      <div class="filters">
        <div class="search-box">
          <input v-model="searchQuery" placeholder="搜索考试..." />
          <i class="fas fa-search"></i>
        </div>
        <select v-model="statusFilter" class="status-filter">
          <option value="">所有状态</option>
          <option value="未开始">未开始</option>
          <option value="进行中">进行中</option>
          <option value="已结束">已结束</option>
        </select>
      </div>
    </div>

    <div class="exams-grid">
      <div v-for="exam in filteredExams" :key="exam.id" class="exam-card" :class="getStatusClass(exam.status)">
        <div class="exam-header">
          <h3>{{ exam.title }}</h3>
          <span class="exam-status">{{ exam.status }}</span>
        </div>
        <div class="exam-details">
          <div class="exam-info">
            <p><i class="fas fa-calendar-alt"></i> 开始: {{ formatDate(exam.startTime) }}</p>
            <p><i class="fas fa-calendar-check"></i> 结束: {{ formatDate(exam.endTime) }}</p>
            <p><i class="fas fa-clock"></i> 时长: {{ calculateDuration(exam.startTime, exam.endTime) }}</p>
            <p><i class="fas fa-users"></i> 参与人数: {{ exam.participantCount || 0 }}</p>
          </div>
          <div class="exam-progress" v-if="exam.status === '进行中'">
            <div class="progress-label">进度</div>
            <div class="progress-bar">
              <div class="progress" :style="{ width: calculateProgress(exam.startTime, exam.endTime) + '%' }"></div>
            </div>
            <div class="progress-value">{{ calculateProgress(exam.startTime, exam.endTime) }}%</div>
          </div>
        </div>
        <div class="exam-actions">
          <button @click="editExam(exam)" class="btn btn-sm btn-secondary" title="编辑考试">
            <i class="fas fa-edit"></i>
          </button>
          <button @click="duplicateExam(exam)" class="btn btn-sm btn-info" title="复制考试">
            <i class="fas fa-copy"></i>
          </button>
          <button @click="viewResults(exam.id)" class="btn btn-sm btn-success" title="查看结果">
            <i class="fas fa-chart-bar"></i>
          </button>
          <button @click="deleteExam(exam.id)" class="btn btn-sm btn-danger" title="删除考试">
            <i class="fas fa-trash"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 没有考试时显示 -->
    <div v-if="filteredExams.length === 0" class="no-exams">
      <i class="fas fa-clipboard-list"></i>
      <p>没有找到符合条件的考试</p>
      <button @click="showAddExamModal" class="btn btn-primary">添加新考试</button>
    </div>

    <!-- Add/Edit Exam Modal -->
    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ editingExam ? '编辑考试' : '添加新考试' }}</h3>
          <button @click="closeModal" class="close-button">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <form @submit.prevent="saveExam" class="exam-form">
          <div class="form-group">
            <label for="examName">考试名称:</label>
            <input type="text" id="examName" v-model="currentExam.title" required>
          </div>
          <div class="form-group">
            <label for="startTime">开始时间:</label>
            <input type="datetime-local" id="startTime" v-model="currentExam.startTime" required>
          </div>
          <div class="form-group">
            <label for="endTime">结束时间:</label>
            <input type="datetime-local" id="endTime" v-model="currentExam.endTime" required>
          </div>
          <div class="form-group">
            <label for="status">状态:</label>
            <select id="status" v-model="currentExam.status">
              <option value="未开始">未开始</option>
              <option value="进行中">进行中</option>
              <option value="已结束">已结束</option>
            </select>
          </div>
          <div class="form-group">
            <label for="description">考试说明:</label>
            <textarea id="description" v-model="currentExam.description" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label for="questionBanks">选择题库:</label>
            <div class="checkbox-group">
              <div v-for="bank in questionBanks" :key="bank.id" class="checkbox-item">
                <input type="checkbox" :id="'bank-' + bank.id" v-model="currentExam.selectedBanks" :value="bank.id">
                <label :for="'bank-' + bank.id">{{ bank.name }}</label>
              </div>
            </div>
          </div>
          <div class="form-actions">
            <button type="submit" class="btn btn-primary">保存</button>
            <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
          </div>
        </form>
      </div>
    </div>
    <Pagination
      :totalItems="pageTotal"
      :itemsPerPage="6"
      :initialPage="1"
      @page-change="handlePageChange"
    />
    <Loading
      :size="60"
      color="#4CAF50"
      shadowColor="#A5D6A7"
      :speed="0.6"
      :loading="loading"
      backgroundColor="rgba(255, 255, 255, 0.8)">
</Loading>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter,useRoute} from 'vue-router';
import { ExamService } from '@/api/exam';
const router = useRouter();
const route=useRoute();
const loading=ref(false)
const currentPage=ref(1)
const pageTotal=ref(1);
// 模拟数据
const exams = ref([
  {
    id: 1,
    name: '2023年春季Java考试',
    startTime: '2023-06-01T09:00',
    endTime: '2023-06-01T11:00',
    status: '已结束',
    description: 'Java基础知识考试，包括语法、面向对象和集合框架等内容。',
    participantCount: 45,
    selectedBanks: [1]
  },
  {
    id: 2,
    name: '2023年秋季Python考试',
    startTime: '2023-12-15T14:00',
    endTime: '2023-12-15T16:00',
    status: '未开始',
    description: 'Python编程基础考试，涵盖基本语法、数据结构和函数等内容。',
    participantCount: 32,
    selectedBanks: [2]
  },
  {
    id: 3,
    name: '2023年Web前端技术考试',
    startTime: '2023-09-10T10:00',
    endTime: '2023-09-10T12:00',
    status: '已结束',
    description: 'Web前端技术考试，包括HTML、CSS和JavaScript等内容。',
    participantCount: 38,
    selectedBanks: [1, 2]
  },
  {
    id: 4,
    name: '2023年数据库原理考试',
    startTime: new Date(Date.now() - 3600000).toISOString().slice(0, 16),
    endTime: new Date(Date.now() + 3600000).toISOString().slice(0, 16),
    status: '进行中',
    description: '数据库原理考试，包括SQL语法、数据库设计和事务管理等内容。',
    participantCount: 27,
    selectedBanks: [2]
  },
  {
            "id": "1834555138886270977",
            "name": "niubbbbb - 考试",
            "duration": "50分钟",
            "totalScore": 40,
            "passScore": 60,
            "status": 3,
            "startTime": "2024-09-01",
            "endTime": "2024-10-26"
  },

]);

const questionBanks = ref([
  { id: 1, name: "JavaScript基础" },
  { id: 2, name: "Vue.js进阶" },
]);

const showModal = ref(false);
const editingExam = ref(null);
const searchQuery = ref('');
const statusFilter = ref('');

const currentExam = ref({
  title: '',
  startTime: '',
  endTime: '',
  status: '未开始',
  description: '',
  selectedBanks: []
});








const filteredExams = computed(() => {
  let result = exams.value;

  // 应用搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(exam =>
      exam.title.toLowerCase().includes(query) ||
      (exam.description && exam.description.toLowerCase().includes(query))
    );
  }

  // 应用状态过滤
  if (statusFilter.value) {
    result = result.filter(exam => exam.status === statusFilter.value);
  }

  return result;
});

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString();
};

const calculateDuration = (startTime, endTime) => {
  const start = new Date(startTime);
  const end = new Date(endTime);
  const durationMs = end - start;
  const hours = Math.floor(durationMs / (1000 * 60 * 60));
  const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));

  return `${hours}小时${minutes > 0 ? ` ${minutes}分钟` : ''}`;
};

const calculateProgress = (startTime, endTime) => {
  const start = new Date(startTime);
  const end = new Date(endTime);
  const now = new Date();

  if (now < start) return 0;
  if (now > end) return 100;

  const total = end - start;
  const elapsed = now - start;
  return Math.round((elapsed / total) * 100);
};

const getStatusClass = (status) => {
  switch (status) {
    case '未开始': return 'status-pending';
    case '进行中': return 'status-ongoing';
    case '已结束': return 'status-completed';
    default: return '';
  }
};

const showAddExamModal = () => {
  router.push('/paperSelect')
};

onMounted(() => {
loadExam(currentPage.value);
});

const loadExam = async (page) => {
  loading.value =true
  try{
    const response=await ExamService.pageExam({page:page,pageSize:6});
  exams.value=response.data;
  pageTotal.value=response.map.totalPage;
  }
  finally{ loading.value =false;}


};
const  handlePageChange = (pageData)=>{
  currentPage.value = pageData.page;
  loadExam(currentPage.value);
};
const editExam = (exam) => {
  editingExam.value = exam;
  currentExam.value = { ...exam };
  showModal.value = true;
};

const duplicateExam = (exam) => {
  const newExam = {
    ...exam,
    id: Math.max(...exams.value.map(e => e.id)) + 1,
    title: `${exam.title} (复制)`,
    status: '未开始'
  };
  exams.value.push(newExam);
};

const viewResults = (id) => {
  router.push(`/dashboard/results?examId=${id}`);
};

const deleteExam = async (id) => {
  if (confirm('确定要删除这个考试吗？')) {
    exams.value = exams.value.filter(e => e.id !== id);
  }

   await ExamService.deleteExam(id);

};

const saveExam = () => {
  // 验证结束时间晚于开始时间
  const start = new Date(currentExam.value.startTime);
  const end = new Date(currentExam.value.endTime);

  if (end <= start) {
    alert('结束时间必须晚于开始时间');
    return;
  }

  if (editingExam.value) {
    const index = exams.value.findIndex(e => e.id === editingExam.value.id);
    if (index !== -1) {
      exams.value[index] = { ...currentExam.value, id: editingExam.value.id };
    }
  } else {
    const newId = Math.max(...exams.value.map(e => e.id), 0) + 1;
    exams.value.push({ ...currentExam.value, id: newId, participantCount: 0 });
  }
  closeModal();
};

const closeModal = () => {
  showModal.value = false;
  editingExam.value = null;
};
</script>

<style scoped>
.exams-management {
  padding: 1rem;
  width: 100%;
}

.page-title {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  color: var(--primary-color);
  border-bottom: 2px solid var(--primary-color);
  padding-bottom: 0.5rem;
}

.actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.filters {
  display: flex;
  gap: 1rem;
}

.search-box {
  position: relative;
}

.search-box input {
  padding: 0.5rem 0.5rem 0.5rem 2rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 1rem;
  width: 250px;
}

.search-box i {
  position: absolute;
  left: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  color: #6c757d;
}

.status-filter {
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 1rem;
}

.exams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
}

.exam-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
  border-top: 4px solid #ccc;
}

.exam-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.status-pending {
  border-top-color: #1890ff;
}

.status-ongoing {
  border-top-color: #52c41a;
}

.status-completed {
  border-top-color: #d9d9d9;
}

.exam-header {
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--border-color);
}

.exam-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: #333;
}

.exam-status {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}

.status-pending .exam-status {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-ongoing .exam-status {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-completed .exam-status {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.exam-details {
  padding: 1rem;
}

.exam-info p {
  margin: 0.5rem 0;
  display: flex;
  align-items: center;
}

.exam-info i {
  width: 20px;
  margin-right: 0.5rem;
  color: #8c8c8c;
}

.exam-progress {
  margin-top: 1rem;
}

.progress-label {
  font-size: 0.9rem;
  margin-bottom: 0.25rem;
  color: #8c8c8c;
}

.progress-bar {
  height: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #52c41a;
}

.progress-value {
  text-align: right;
  font-size: 0.8rem;
  margin-top: 0.25rem;
  color: #8c8c8c;
}

.exam-actions {
  padding: 1rem;
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  border-top: 1px solid var(--border-color);
}

.no-exams {
  text-align: center;
  padding: 3rem;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-top: 1rem;
}

.no-exams i {
  font-size: 3rem;
  color: #d9d9d9;
  margin-bottom: 1rem;
}

.no-exams p {
  color: #8c8c8c;
  margin-bottom: 1rem;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid var(--border-color);
}

.close-button {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #6c757d;
}

.exam-form {
  padding: 1rem;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 1rem;
}

.checkbox-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.5rem;
}

.checkbox-item {
  display: flex;
  align-items: center;
}

.checkbox-item input {
  margin-right: 0.5rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

@media (max-width: 768px) {
  .actions {
      flex-direction: column;
      align-items: stretch;
      gap: 1rem;
  }

  .filters {
      flex-direction: column;
      gap: 0.5rem;
  }

  .search-box input {
      width: 100%;
  }

  .checkbox-group {
      grid-template-columns: 1fr;
  }
}

</style>
